/*
 * @Description:
 * @Author: ldx
 * @Date: 2022-04-20 11:51:40
 * @LastEditors: ldx
 * @LastEditTime: 2022-09-29 22:35:54
 */
import { atom, AtomEffect, selector } from 'recoil'

import { getStorage } from '@/utils'

import { Mode } from '..'

// 官网链接 https://www.recoiljs.cn/docs/basic-tutorial/atoms
// 通过atom包裹的内容, 通过key获取对用的数据 key值与设置的属性值一致 default为默认数据
// 通过 useRecoilValue 获取数据
// const factoryName = useRecoilValue(factoryName)
// 通过 useSetRecoilState 设置数据
// const setFactoryName = useSetRecoilState(factoryName)
// 通过hook的方式
// const [factoryName, setFactoryName] = useRecoilState(factoryName);

// 使用selector监听某个状态 输出其他的内容
const sleep = (time: number, info: any) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('info', info)
      resolve([])
    }, time)
  })
}

const localStorageEffect =
  (key: string): AtomEffect<string | null> =>
  ({ setSelf, onSet }) => {
    const savedValue = getStorage(key)
    if (savedValue != null) {
      setSelf(savedValue)
    }
    onSet((newValue) => {
      // console.log('newValue,oldValue:', newValue, oldValue)
      if (!newValue) {
        localStorage.removeItem(key)
        sessionStorage.removeItem(key)
      }
    })
  }

const userAuths = selector({
  key: 'userAuths',
  get: async ({ get }) => {
    // get监听对应的状态 例如获取列表数据 返回对应的页码 总数 列表内容等
    const info = get(userInfo)
    const auth = await sleep(2000, info) // 代替接口
    return auth || []
  }
})

const auths = atom({
  key: 'auths',
  default: []
})
const permissions = atom({
  key: 'permissions',
  default: 'permission'
})
const userInfo = atom({
  key: 'userInfo',
  default: {}
})
const isLogin = atom({
  key: 'isLogin',
  default: null,
  effects_UNSTABLE: [localStorageEffect('token')]
})
const mode = atom<Mode>({
  key: 'mode',
  default: 'vertical' // vertical | horizontal
})
const publicKey = atom({
  key: 'public-key',
  default: '' // vertical | horizontal
  // de: true
})
export default {
  mode,
  userAuths,
  auths,
  userInfo,
  isLogin,
  permissions,
  publicKey
}
